package Controller

import (
	"computer_set/global"
	"computer_set/model"
	"github.com/gin-gonic/gin"
	"sort"
	"strconv"
	"strings"
	"sync"
)

func QueryRanges(rangeStr string, wg *sync.WaitGroup, result chan model.BookContext) {
	defer wg.Done()
	parts := strings.Split(rangeStr, "-")
	start, _ := strconv.Atoi(parts[0])
	end, _ := strconv.Atoi(parts[1])

	db := global.DB
	sql := "select * from bencaogangmu limit ? offset ?"
	rows, err := db.Raw(sql, end-start, start-1).Rows()
	if err != nil {
		return
	}
	defer rows.Close()

	for rows.Next() {
		var book model.BookContext
		if err := rows.Scan(&book.Id, &book.HerbName, &book.Origin, &book.Description, &book.Efficacy, &book.History); err != nil {
			continue
		}
		result <- book
	}
}

// 新增排序结构体
type OriginCount struct {
	Origin string
	Count  int
	Books  []model.BookContext
}

func groupBooksByField(c *gin.Context, field string) {
	var wg sync.WaitGroup
	result := make(chan model.BookContext, 100)
	ranges := []string{"1-100", "101-200", "201-300", "301-400", "401-500"}

	for _, rangeStr := range ranges {
		wg.Add(1)
		go QueryRanges(rangeStr, &wg, result)
	}

	go func() {
		wg.Wait()
		close(result)
	}()

	groupedMap := make(map[string][]model.BookContext)

	for book := range result {
		switch field {
		case "Origin":
			groupedMap[book.Origin] = append(groupedMap[book.Origin], book)
		case "Efficacy":
			groupedMap[book.Efficacy] = append(groupedMap[book.Efficacy], book)
		}
	}

	// 新增排序逻辑（仅对Origin字段生效）
	if field == "Origin" {
		// 转换map为可排序的slice
		var origins []OriginCount
		for origin, books := range groupedMap {
			origins = append(origins, OriginCount{
				Origin: origin,
				Count:  len(books),
				Books:  books,
			})
		}

		// 按数量降序排序
		sort.Slice(origins, func(i, j int) bool {
			return origins[i].Count > origins[j].Count
		})

		// 转换回有序map（需Go1.18+）
		orderedMap := make([]gin.H, 0)
		for _, item := range origins {
			orderedMap = append(orderedMap, gin.H{
				"origin": item.Origin,
				"count":  item.Count,
				"books":  item.Books,
			})
		}
		c.JSON(200, orderedMap)
	} else {
		c.JSON(200, groupedMap)
	}
}

func GetAllOrigin(c *gin.Context) {
	groupBooksByField(c, "Origin")
}

func GetAllEfficacy(c *gin.Context) {
	groupBooksByField(c, "Efficacy")
}
